﻿using SqlSugar;
using System.Runtime.CompilerServices;
using Zhp.Common.Helper;
using Zhp.Common.WebApp;
using Zhp.SqlSugar.Repository;

namespace Zhp.SqlSugar.Entity
{
    /// <summary>
    /// 只包含主键，删除额外字段
    /// </summary>
    /// <typeparam name="TEntity"></typeparam>
    /// <typeparam name="TKey"></typeparam>
    public abstract class RootEntity<TEntity, TKey> : RootEntityReadOnly<TEntity> where TEntity : RootEntity<TEntity, TKey>, new()
    {
        private static IBaseRepository<TEntity> repository = ApplicationHelper.GetService<IBaseRepository<TEntity>>();

        /// <summary>
        /// 主键
        /// </summary>
        [SugarColumn(IsPrimaryKey = true, ColumnDescription = "ID主键")]
        public virtual TKey Id { get; set; }

        #region 扩展方法：主键查询，新增，修改，删除

        /// <summary>
        /// 主键查询
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public static TEntity Find(TKey id)
        {
            return repository.GetById(id);
        }

        /// <summary>
        /// 主键查询
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public virtual async Task<TEntity> FindAsync(TKey id)
        {
            return await repository.GetByIdAsync(id);
        }

        /// <summary>
        /// 新增
        /// </summary>
        /// <returns></returns>
        public virtual bool Insert()
        {
            return repository.Insert(this as TEntity);
        }

        /// <summary>
        /// 新增
        /// </summary>
        /// <returns></returns>
        public virtual async Task<bool> InsertAsync()
        {
            return await repository.InsertAsync(this as TEntity);
        }

        /// <summary>
        /// 修改
        /// </summary>
        /// <returns></returns>
        public virtual bool Update()
        {
            return repository.Update(this as TEntity);
        }

        /// <summary>
        /// 修改
        /// </summary>
        /// <returns></returns>
        public virtual async Task<bool> UpdateAsync()
        {
            return await repository.UpdateAsync(this as TEntity);
        }

        /// <summary>
        /// 删除
        /// </summary>
        /// <returns></returns>
        public virtual bool Delete()
        {
            return repository.Delete(this as TEntity);
        }

        /// <summary>
        /// 删除
        /// </summary>
        /// <returns></returns>
        public virtual async Task<bool> DeleteAsync()
        {
            return await repository.DeleteAsync(this as TEntity);
        }

        #endregion
    }
}
